// pages/outvisit/task/uploadList.js
const innerAudioContext = wx.createInnerAudioContext();
var pagetitle = ["", "照片", "视频", "录音"];
var api = require("../../../utils/api.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prePage: {},//上一个页面实例对象
    userId: 0,//用户ID
    outvisitTaskId: 0,//外访任务ID
    type: 0,//文件类型
    id: 0,//催收案件ID
    floder: "外景照片",
    files: [],//文件列表
    photoFiles: [],//照片文件列表
    pictureFiles: [],
    photoFilesMode: [
      { isMust: false, title: "街景", files: [] },
      { isMust: false, title: "小区大门", files: [] },
      { isMust: false, title: "街道号", files: [] },
      { isMust: false, title: "小区名称", files: [] },
      { isMust: false, title: "小区景观", files: [] },
      { isMust: false, title: "楼栋外观", files: [] },
      { isMust: false, title: "栋号", files: [] },
      { isMust: false, title: "单元号", files: [] },
      { isMust: false, title: "单元入口", files: [] },
      { isMust: false, title: "楼层号", files: [] },
      { isMust: false, title: "可比实例外观照片", files: [] },
    ],//照片文件列表模板
    videoSrc: "",//视频路径
    selectRecordIsHide: true,//选择录音是不是隐藏
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    var userId = wx.getStorageSync("userId");
    var outvisitTaskId = options.outvisitTaskId;
    var type = options.type;
    var id = options.id;
    // 设置标题
    wx.setNavigationBarTitle({
      title: '外景照片'
    });

    // 设置文件类型和文件列表
    that.setData({
      userId: userId,
      outvisitTaskId: outvisitTaskId,
      type: type,
      id: id,
    });

    var filesList = that.getFiles(1);
    // 获取文件列表
    var files = filesList[1];
    // 获取照片文件列表
    var photoFiles = filesList[1];

    that.setData({
      files: files,
      photoFiles: photoFiles,
    });
  },

  // 设置文件列表
  setFiles: function (files) {
    var that = this;
    var pictureFiles = [];//照片列表
    var videoFiles = [];//视频列表
    var recordFiles = [];//录音列表
    for (var i = 0; i < files.length; i++) {
      if (files[i].fileType==1){
        var file = files[i];
        if (!file.photoType) {
          file.photoType = 1;
        }
        pictureFiles.push(file);
      } else if (files[i].fileType == 2) {
        videoFiles.push(files[i]);
      } else if (files[i].fileType == 3) {
        recordFiles.push(files[i]);
      }
    }
    that.setData({
      pictureFiles: pictureFiles,
      videoFiles: videoFiles,
      recordFiles: recordFiles
    });
  },

  // 设置表单下拉框默认值（浦发）
  setPickerValuePuFa: function (data) {
    var that = this;
    var pickerValuePuFa = that.data.pickerValuePuFa;
    if (data.ccode) {
      var ccodeList = that.data.ccodeList;
      for (var i = 0; i < ccodeList.length; i++) {
        if (data.ccode == ccodeList[i].id) {
          pickerValuePuFa[0] = i;
        }
      }
      // 获取外访场景列表（浦发）
      wx.showLoading({
        title: '加载中',
      });//显示加载中
      api.getSceneData(that.data.ccodeList[pickerValuePuFa[0]].id).then(res => {
        if (res.code == 0) {
          wx.hideLoading();//隐藏加载中
          var sceneData = res.data;
          var rcodeList = [];
          if (sceneData) {
            rcodeList = sceneData;
          }
          if (data.rcode) {
            for (var i = 0; i < rcodeList.length; i++) {
              if (data.rcode == rcodeList[i].id) {
                pickerValuePuFa[1] = i;
              }
            }
          }
          that.setData({
            pickerValuePuFa: pickerValuePuFa,
            rcodeList: rcodeList
          });
        }
      });
    }
  },

  // 获取文件列表
  getFiles: function (type) {
    type = 1;
    var that = this;
    var files = [];
    var photoFiles = [];

    // 获取照片文件列表
    photoFiles = that.getPhotoFiles(that.data.pictureFiles);

    return [files, photoFiles];
  },

  // 获取照片文件列表
  getPhotoFiles: function () {
    var that = this;
    var photoFiles = [
      { isMust: false, title: "街景", files: [] },
      { isMust: false, title: "小区大门", files: [] },
      { isMust: false, title: "街道号", files: [] },
      { isMust: false, title: "小区名称", files: [] },
      { isMust: false, title: "小区景观", files: [] },
      { isMust: false, title: "楼栋外观", files: [] },
      { isMust: false, title: "栋号", files: [] },
      { isMust: false, title: "单元号", files: [] },
      { isMust: false, title: "单元入口", files: [] },
      { isMust: false, title: "楼层号", files: [] },
      { isMust: false, title: "可比实例外观照片", files: [] },
    ];

    api.getSurveyImgs(that.data.id,"外景照片",'').then(res => {
      if (res.code == 0) {
        //wx.hideLoading();
        var data = res.data;
        // 更新数据
        that.setData({
          surveyColumnValList: data.colValueList,
          pickerValue: data.pickerValue
        }, () => {
          //...
        });
      }
    });

    api.getSurveyImgs(that.data.id,"外景照片",'').then(res => {
      if (res.code == 0) {
        //wx.hideLoading();
        var data = res.data;
        for (var i = 0; i < photoFiles.length; i++) {
          var fileList = [];
          for (var j=0; j<data.length; j++) {
            if (data[j].housetype == photoFiles[i].title) {
              fileList.push(data[j].path);
            }
          }
          //console.log(fileList);
          if (fileList.length > 0) {
            photoFiles[i].files.push(fileList);
          }
        }

        that.setData({
          photoFiles: photoFiles,
        }, () => {
          //console.log(that.data.photoFiles);
        });
      }
    });
  },

  // 选择文件
  selectFiles: function (e) {
    // 防止连续点击
    if (this.justClick) {
      return;
    }
    this.justClick = true;
    setTimeout(() => {
      this.justClick = false;
    }, 500);

    var photoType = e.currentTarget.dataset.phototype;//照片类型
    var index = e.currentTarget.dataset.index;//照片类型

    // 选择图片
    if (this.data.photoFiles[index].files.length >= 12) {
      wx.showToast({
        title: '已达图片最大上传数，请删除部分后再上传',
        icon: 'none'
      });
    } else {
      this.selectPicture(photoType,index);
    }
  },

  // 选择图片
  selectPicture: function (photoType,photoTypeIndex){
    var that = this;
    var photoType = photoType;

    wx.chooseMedia({
      count: 9, // 默认9,v2.25.0后最大到20
      mediaType: ['image'],
      sourceType: ['album', 'camera'],  // 可以拍摄或从相册中选择
      sizeType: ['original', 'compressed'],
      success: function (res) {
        // var tempFilePaths = res.tempFilePaths;
        var tempFilePaths = res.tempFiles;

        //启动上传等待中...
        wx.showLoading({
          title: "正在上传..."
        });
        // 文件数量，用于判断是否超过最大上传数
        var filesLength = that.data.photoFiles[photoTypeIndex].files.length;
        var uploadCount = 0;
        var files = [];
        for (var i = 0, h = tempFilePaths.length; i < h && i + filesLength < 12; i++) {
          api.uploadFile(tempFilePaths[i].tempFilePath, that.data.id, photoType, that.data.floder).then(res => {
            uploadCount++;

            var data = JSON.parse(res.data);
            if (data.code == 0) {
              wx.hideLoading();
              if (data.msg == '成功') {
                wx.showToast({
                  title: '上传成功',
                  icon: 'none'
                });
              }
              else if (data.msg == '重复') {
                wx.showToast({
                  title: '相同图片请勿重复上传',
                  icon: 'none'
                });
              }

              var filesList = that.getFiles(1);
              // 获取文件列表
              var files = filesList[1];
              // 获取照片文件列表
              var photoFiles = filesList[1];

              that.setData({
                files: files,
                photoFiles: photoFiles,
              });
            }
          }).catch(res => {
            uploadCount++;
            // 保存图片
            // that.savePicture(uploadCount, tempFilePaths.length, filesLength, files);

            wx.hideLoading();
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            });
          });
        }

        that.getPhotoFiles(that.data.pictureFiles);
      }
    });
  },

  getSurveyImgs:function(id,floder) {
    api.getSurveyImgs(id,floder).then(res => {
      if (res.code == 0) {
        wx.hideLoading();
        var data = res.data;

        if (data) {

        }
      }
    });
  },

  // 保存图片
  savePicture: function (uploadCount, tempFilePathsLength, filesLength, files) {
    var that = this;
    //如果是最后一个,则保存
    if (uploadCount == tempFilePathsLength || uploadCount + filesLength >= 12) {
      if (files.length > 0) {
        that.formSubmit(files);
      } else {
        wx.hideLoading();
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }
    }
  },

  // 选择视频
  selectVideo:function(){
    var that = this;
    wx.chooseVideo({
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        //启动上传等待中...
        wx.showLoading({
          title: "正在上传..."
        });
        api.uploadFile(tempFilePath, that.data.id, that.data.type, that.data.floder).then(res => {
          var data = JSON.parse(res.data);
          if (data.code == 0) {
            that.formSubmit([{
              filePath: data.data[0].filePath,
              fileType: that.data.type
            }]);
          } else {
            wx.hideLoading();
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        }).catch(res => {
          wx.hideLoading();
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        });
      }
    });
  },

  // 提交表单
  formSubmit: function (file) {
    var that = this;

    submitData.files = files;
  },

  // 预览文件
  preview:function(e){
    var type = this.data.type;
    var photoType = e.currentTarget.dataset.photoType;//当前照片文件的类型
    var index = e.currentTarget.dataset.index;//当前照片文件的类型
    var filePath = e.currentTarget.dataset.path;//当前文件的链接

    // 预览图片
    this.previewPicture(photoType, filePath, index);
  },

  // 预览图片
  previewPicture: function (photoType, filePath, index) {
    // 获取图片链接列表
    var urls=[];//图片链接列表
    urls.push(filePath);

    // 开启图片预览
    wx.previewImage({
      current: filePath, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },

  // 预览视频
  previewVideo: function (filePath) {
    var videoContext = wx.createVideoContext("previewVideo",this);
    this.setData({
      videoSrc: filePath
    }, res => {
      videoContext.requestFullScreen({ direction: 0 });
    });
  },

  // 预览视频全屏切换事件
  previewVideoFullscreen:function(e){
    if (!e.detail.fullScreen){
      this.setData({
        videoSrc:""
      });
    }
  },

  // 预览音频
  previewRecord: function (filePath){
    innerAudioContext.src = filePath;
    innerAudioContext.play();
    innerAudioContext.onPlay(() => {
      wx.showToast({
        title: '开始播放',
        icon: 'none'
      });
    });
    innerAudioContext.onError(res => {
      wx.showToast({
        title: '播放失败',
        icon: 'none'
      });
    });
    innerAudioContext.onEnded(res => {
      wx.showToast({
        title: '播放结束',
        icon: 'none'
      });
    });
  },

  // 删除文件
  delFile:function(e){
    var that = this;
    wx.showModal({
      title: "提示",
      content: "确定删除吗？",
      success: function (sm) {
        var photoType = e.currentTarget.dataset.photoType;//当前照片文件的类型
        var index = e.currentTarget.dataset.index;//当前文件的下标
        var path = e.currentTarget.dataset.path;

        if (sm.confirm) {
          wx.showLoading({
            title: '删除中...',
          });
          api.deleteImage(that.data.id, photoType, that.data.floder, path).then(res => {
            if (res.code == 0) {
              wx.hideLoading();

              var filesList = that.getFiles(1);
              // 获取文件列表
              var files = filesList[1];
              // 获取照片文件列表
              var photoFiles = filesList[1];

              that.setData({
                files: files,
                photoFiles: photoFiles,
              });
            }
          });
        }
      }
    })
  },

  // 提交数据
  submitData:function(){
    var that = this;
    var type = that.data.type;
  },

  // 确定提交
  submit: function () {
    var that = this;
    // 提交数据
    that.submitData();

    var photoFiles = this.data.photoFiles;
    for (var i = 0; i < photoFiles.length; i++) {
      if (photoFiles[i].isMust){
        if (photoFiles[i].files.length == 0) {
          wx.showToast({
            title: '['+photoFiles[i].title+']照片为必填，必须上传！',
            icon: 'none'
          });

          return;
        }
      }
    }

    api.surveyColumnComplete(that.data.id, "外景照片", that.data.userId).then(res => {
      if (res.code == 0) {
        wx.showToast({
          title: '上传成功',
          icon: 'none'
        });

      }
    }).catch(res => {
      wx.hideLoading();
      wx.showToast({
        title: '上传失败',
        icon: 'none'
      });
    });

    let pages = getCurrentPages();//当前页面
    console.log(pages);
    let prevPage = pages[pages.length - 2];//上一页面
    console.log(prevPage);
    prevPage.getSurveyColumnComplete();
    // 返回
    wx.navigateBack({
      delta: 1,
    });
  },

  // 选择录音显示与隐藏
  selectRecordShowOrHide: function () {
    var selectRecordIsHide = this.data.selectRecordIsHide;
    if (selectRecordIsHide) {
      selectRecordIsHide = false;
    } else {
      selectRecordIsHide = true;
    }
    this.setData({
      selectRecordIsHide: selectRecordIsHide
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    innerAudioContext.stop();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    innerAudioContext.stop();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
